<template>
	<div ref="container">
		<div style="position: absolute; z-index: 10" class="flex-center w100 h100" v-show="loading">
			<dv-decoration :scale="2">
				<span class="fw" style="font-size: 30px"> {{ percentComplete }}% </span>
			</dv-decoration>
		</div>
		<div class="geo-box" style="right: 10px; bottom: 10px">
			<span>经度：{{ long_lat.x }}</span>
			<span>纬度：{{ long_lat.z }}</span>
			<span>海拔：{{ long_lat.y }}</span>
		</div>
	</div>
</template>

<script setup name="tunnelling">
// 引入全局资源
import { DBUtil } from '@u/indexedDB'
import { throttle } from '@u/util'
import { useResizeObserver, THREE, GLTFloaderFn, clock, textureLoader, MapControls, mixersFn, rendererFn, labelRendererFn } from '@u/threeMinx'

let container = shallowRef(null), // 模型渲染的Demo节点
	renderer, //  WebGLRenderer渲染器
	scene, // 场景
	camera, // 相机
	controls,
	labelRenderer,
	loading = ref(false),
	percentComplete = ref(0)

// 组件宽高
let width, height
useResizeObserver(container, (entries) => {
	width = entries[0].contentRect.width
	height = entries[0].contentRect.height
	camera.aspect = width / height
	camera.updateProjectionMatrix()
	renderer.setSize(width, height)
	labelRenderer.setSize(width, height)
})
// 初始化生命周期
onMounted(() => {
	loading.value = true
	init()
})
onBeforeUnmount(() => {
	cancelAnimationFrame(requestAnimationFrameIndex)
	// 释放显存
	renderer?.dispose()
	// 释放内存
	scene.clear()
	container = null
	scene = null
	labelRenderer = null
})

function init() {
	// 场景
	scene = new THREE.Scene()
	const background = textureLoader.load(`${import.meta.env.VITE_APP_BASE_BASE ?? '/'}model/blue2.jpg`)
	background.colorSpace = THREE.SRGBColorSpace
	scene.background = background
	// 相机
	camera = new THREE.PerspectiveCamera(45, container.value.offsetWidth / container.value.offsetHeight, 1, 2000)
	camera.position.set(109.63, 86.72, 96.25)
	scene.add(camera)

	renderer = rendererFn(container)
	labelRenderer = labelRendererFn(container)

	// 控制器
	controls = new MapControls(camera, renderer.domElement)
	controls.target.set(110.48293056262132, -50.336801686323525, -3.7927571043980493)
	controls.minPolarAngle = 0
	controls.maxPolarAngle = Math.PI / 2

	// 加载器
	loaderFn()
}
let model,
	mixers = [],
	centerPoint = [117.076481, 0, 31.660061]

function loaderFn() {
	new DBUtil().get(`${import.meta.env.VITE_APP_BASE_BASE || '/'}model/巷道综采面.glb`).then((blob) => {
		let url = URL.createObjectURL(blob)
		GLTFloaderFn.load(
			url,
			(object) => {
				loading.value = false
				model = object.scene
				model.position.set(...centerPoint)
				loadPlan(model.position)
				scene.add(model)
				// 流线
				tubeFn()
				// 灯光
				lights()
				//动画
				mixers.push(mixersFn(object))
				// 渲染器
				render()
			},
			(xhr) => {
				if (xhr.lengthComputable) percentComplete.value = Math.round((xhr.loaded / xhr.total) * 100, 2)
			}
		)
	})
}

// 添加管线
let tube1
function tubeFn() {
	// 创建组合曲线对象CurvePath
	let curve = new THREE.CurvePath()
	// 把多个线条插入到CurvePath中
	curve.curves.push(
		new THREE.LineCurve3(new THREE.Vector3(89.77380574060942, 0, 72.93748384923792), new THREE.Vector3(89.78317699663523, 0, 32.12647226937418)),
		new THREE.LineCurve3(new THREE.Vector3(89.78317699663523, 0, 32.12647226937418), new THREE.Vector3(173.29293620343606, 0, 32.14087952295474))
	)
	// 贴图
	let texture = textureLoader.load(`${import.meta.env.VITE_APP_BASE_BASE || '/'}model/line1.png`)
	// 设置阵列模式为 RepeatWrapping
	texture.wrapS = texture.wrapT = THREE.RepeatWrapping
	// 设置x方向的偏移(沿着管道路径方向)，y方向默认1
	texture.repeat.set(50, 2)
	tube1 = new THREE.Mesh(
		new THREE.TubeGeometry(curve, 1000, 0.3, 8),
		new THREE.MeshStandardMaterial({ opacity: 1, map: texture, transparent: true, depthWrite: true, depthTest: true })
	)
	scene.add(tube1)
}

/**
 * @description 构建平面
 */
let plane
function loadPlan({ x, y, z }) {
	// 创建平面
	plane = new THREE.Mesh(
		new THREE.PlaneGeometry(1000, 1000),
		new THREE.MeshLambertMaterial({
			color: 0xffffff,
			side: THREE.DoubleSide,
			opacity: 0,
			transparent: true
		})
	)
	// 旋转放平
	plane.rotation.x = 0.5 * Math.PI
	plane.position.set(x, y, z)
	scene.add(plane)

	renderer.domElement.addEventListener(
		'mousedown',
		(e) => {
			if (e.button == 2) modelOnClick(e, [plane, model], true)
		},
		false
	)
	renderer.domElement.addEventListener(
		'mousemove',
		(e) => {
			throttle(modelOnClick(e, [plane, model], false))
		},
		false
	)
}

// 鼠标右键点击设置控制器中心坐标
const raycaster = new THREE.Raycaster()
let long_lat = ref({
	x: centerPoint[0].toFixed(4),
	y: centerPoint[1].toFixed(4),
	z: centerPoint[2].toFixed(4)
})
function modelOnClick(e, object, mousedown) {
	const { left: left, top: top, width: width, height: height } = renderer.domElement.getBoundingClientRect()

	const mouse = new THREE.Vector2(((e.clientX - left) / width) * 2 - 1, -((e.clientY - top) / height) * 2 + 1)

	raycaster.setFromCamera(mouse, camera)

	const intersects = raycaster.intersectObjects(object)

	if (intersects.length <= 0) {
		// controls.target.set(object.position.x, object.position.y, object.position.z);
	} else {
		const { x, y, z } = intersects[0].point
		long_lat.value = { x: x.toFixed(4), y: y.toFixed(4), z: z.toFixed(4) }
		if (mousedown) console.log(intersects[0].point)
		// controls.target.set(intersects[0].point.x, intersects[0].point.y, intersects[0].point.z);
	}
}

/**
 * 灯光
 */
function lights() {
	// 自然光
	scene.add(new THREE.AmbientLight('#ffffff', 0.8))
}

// 渲染逻辑
let speed = 0.02,
	requestAnimationFrameIndex
function render() {
	// 线条流动效果
	if (tube1) tube1.material.map.offset.x -= speed
	// label渲染器
	labelRenderer?.render(scene, camera)
	controls.update()
	// 运行动画
	mixers.forEach((mixer) => mixer.update(clock.getDelta()))
	renderer?.render(scene, camera)
	requestAnimationFrameIndex = requestAnimationFrame(render)
}
</script>

<style lang="scss" scoped>
.geo-box {
	position: absolute;
	background-color: rgba(0, 128, 255, 0.5);
	color: #ffffff;
	font-weight: 500;
	border-radius: 1px;
	padding: 4px 8px;
	span {
		margin-right: 8px;
	}
}
</style>
